package cn.edu.zut.controller;

import cn.edu.zut.domin.Book;
import cn.edu.zut.domin.BookLendInfo;
import cn.edu.zut.service.IBookLendInfoService;
import cn.edu.zut.service.IBookService;
import com.github.pagehelper.PageInfo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/bookLendInfo1")
public class BookLendInfoController1 {
    /**
     * 展示所有书
     *
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    ClassPathXmlApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
    IBookService bookService=(IBookService) ac.getBean("bookServiceImpl");
    IBookLendInfoService bookLendInfoService =(IBookLendInfoService)ac.getBean("bookLendInfoServiceImpl");
    @RequestMapping("/findAllBook")
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                @RequestParam(name = "size", required = true, defaultValue = "4") int size) throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Book> books = bookService.findAll(page, size);
        //分页Bean PageInfo就是一个分页的Bean
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        //总页数
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("LentBookInfo");
        return mv;
    }

    @RequestMapping("/findByBook")
    public ModelAndView findBookLendInfoByBook(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                @RequestParam(name = "size", required = true, defaultValue = "4") int size,String bookId) throws Exception {
        ModelAndView mv = new ModelAndView();
        List<BookLendInfo> bookLendInfos = bookLendInfoService.findBookLendInfoByBook(page, size,bookId);
        PageInfo<BookLendInfo> pageInfo = new PageInfo<>(bookLendInfos);
        //总页数等
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("LentBookInfoDetail");
        return mv;
    }

    @RequestMapping("/findBookById")
    public ModelAndView findByBookId(String bookId) throws Exception {
        System.out.println(bookId);
        ModelAndView mv = new ModelAndView();
        List<Book> users = bookService.findBookById(bookId);
        mv.addObject("bookList", users);
        mv.setViewName("LentBookInfo");
        return mv;
    }
    @RequestMapping("/save")
    public String saveLendInfo(BookLendInfo bookLendInfo) throws Exception {
        bookLendInfoService.saveBookLendInfo(bookLendInfo);
        return "redirect:findBookLendInfoAll";
    }
}
